package com.heu.picture.service.impl;

import com.heu.picture.entity.UserPO;
import com.heu.picture.enums.UserRoleEnum;
import com.heu.picture.exception.ErrorCode;
import com.heu.picture.exception.ThrowUtils;
import com.heu.picture.reposity.UserRepository;
import com.heu.picture.request.UserLoginRequest;
import com.heu.picture.request.UserRegisterRequest;
import com.heu.picture.response.UserLoginResponse;
import com.heu.picture.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author Dong & Fei
 * @since 2025-02-20
 */
@Service
public class UserServiceImpl implements IUserService {

    private final String salt = "six";

    @Autowired
    UserRepository userRepository;

    @Override
    public void register(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        ThrowUtils.throwIf(!StringUtils.hasLength(userPassword) || !StringUtils.hasLength(userAccount), ErrorCode.PARAMS_ERROR, "账户名或密码为空!");
        UserPO userByUserAccount = userRepository.getUserByUserAccount(userAccount);
        ThrowUtils.throwIf(null != userByUserAccount, ErrorCode.DUPLICATE_ERROR, "账户名已存在！");
        UserPO userPO = new UserPO();
        userPO.setUserAccount(userAccount);
        String md5 = md5PassWord(userPassword);
        userPO.setUserPassword(md5);
        userPO.setUserRole(UserRoleEnum.USER.getText());
        userRepository.save(userPO);
    }

    @Override
    public UserLoginResponse login(UserLoginRequest request, HttpServletRequest httpServerRequest, HttpServletResponse httpServletResponse) {
        UserPO userPO = userRepository.getuserByUsername(request.getUserAccount(), md5PassWord(request.getUserPassword()));
        ThrowUtils.throwIf(userPO == null, ErrorCode.ACCOUNT_PASSWORD_ERROR);

        httpServerRequest.getSession().setAttribute("user", userPO);
        httpServerRequest.getSession().setMaxInactiveInterval(30 * 60);

        // Set cookie expiration time to 30 minutes
        Cookie cookie = new Cookie("JSESSIONID", httpServerRequest.getSession().getId());
        cookie.setMaxAge(30 * 60);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);

        UserLoginResponse userLoginResponse = new UserLoginResponse();
        userLoginResponse.setName("杨鹏飞");
        return userLoginResponse;
    }

    private String md5PassWord(String userPassword) {
        userPassword = userPassword+salt;
        return DigestUtils.md5DigestAsHex(userPassword.getBytes());
    }
}
